var express = require('express');
const createHttpError = require('http-errors');
var router = express.Router();
var axios = require('axios')
var { UserModel } = require('../untils/model')
var { createToken, checkToken } = require("../untils/token")

/* GET users listing. */
router.get('/', function (req, res, next) {
    res.send('respond with a resource');
});

// router.get("/login", (req, res) => {
//     res.send('login')
// })
router.post("/register/submit", (req, res) => { //注册接口
    var body = req.body
    console.log(body)
    UserModel.findOne({ username: body.usernames }).then(data => {
        if (data) {
            res.send(`<script>alert('用户名已经被注册了...');location.href='/register'</script>`)
        } else {
            UserModel.insertMany(body).then(result => {
                res.send(`<script>alert('注册成功');location.href='/login'</script>`)
            }).catch(err => {
                res.send(`<script>alert('注册失败');location.href='/register'</script>`)
            })
        }
    })
})


router.post("/login/submit", (req, res) => { //登录接口
    var body = req.body
    console.log(body)
    UserModel.findOne(body, { _id: 0 }).then(result => {
        if (result) {
            req.session.username = body.usernames
            console.log(req.session)
            res.send(`<script>alert('登录成功');location.href='/index'</script>`)
        } else {
            res.send(`<script>alert('用户名或密码错误');location.href='/login'</script>`)
        }
    })
})

router.post("/setpass/submit", (req, res) => {

    var body = req.body
    console.log(body.oldpassword)
    if (!req.session.username) {
        req.send(`<script>alert('请重新登录');location.href='/login'</script>`)
    } else {
        UserModel.findOne({ usernames: req.session.username }).then(result => {
            console.log(result, result.password)
            if (result.password == body.oldpassword) {
                UserModel.updateMany({ usernames: req.session.username }, {
                    $set: {
                        password: body.newpassword
                    }
                }).then(data => {
                    res.send(`<script>alert('修改成功，请重新登录');location.href='/login'</script>`)
                })

            } else {
                res.send(`<script>alert('旧密码错误');location.href='/login'</script>`)
            }
        })
    }
})


// UserModel.updateMany({ usernames: session.username }, {
//     $set: {
//         password: body.newpassword
//     }.then(data => {
//         res.json({
//             code: 200,
//             type: 1,
//             msg: "密码修改成功，请重新登录"
//         })
//     })
// })


router.post("/login/dl", (req, res) => { //手机登录接口
    var body = req.body
    console.log(body)
    UserModel.findOne(body, { _id: 0 }).then(result => {
        if (result) {
            var token = createToken({
                username: body.usernames,
                password: body.password
            })
            res.json({
                code: 200,
                type: 1,
                msg: "登录成功",
                token,
                result,
                body
            })
        } else {
            res.json({
                code: 200,
                type: 0,
                msg: "账号或密码错误"
            })
        }
    })
})


router.post("/register/zc", (req, res) => { //手机注册接口
    var body = req.body
    console.log(body)
    UserModel.findOne({ usernames: body.usernames }).then(data => {
        if (data) {
            res.json({
                code: 200,
                type: 0,
                msg: "用户名已注册"
            })
        } else {
            UserModel.insertMany(body).then(result => {
                res.json({
                    type: 1,
                    msg: "注册成功",
                    code: 200
                })
            }).catch(err => {
                res.json({
                    type: 1,
                    msg: "注册失败",
                    code: 200
                })
            })
        }
    })
})


// 获取用户信息
router.get("/getuserinfo", (req, res) => {
    // 判断身份的有效性 
    var username = req.query.username
    console.log(username)
    // checkToken(req, res, ({ username: username }) => {
    console.log(username)
    UserModel.findOne({
        usernames: username
    }).then(result => {
        res.json({
            code: 200,
            msg: "获取用户信息数据成功",
            type: 1,
            result
        })
    }).catch(err => {
        res.json({
            code: 500, // 500 统一失败  
            msg: "服务器异常- 未知错误",
            type: 0,
        })
    })
    // })
})

// 通过手机号查找用户
router.get("/getphoneuser", (req, res) => {

    // 判断身份的有效性 
    UserModel.findOne({
        phone: req.query.phone
    }).then(result => {
        if (result) {
            res.json({
                code: 200,
                msg: "获取用户信息数据成功",
                type: 1,
                result
            })
        } else {
            res.json({
                code: 300,
                msg: "未查询到该用户",
                type: 0,
                result
            })
        }
    }).catch(err => {
        res.json({
            code: 500, // 500 统一失败  
            msg: "服务器异常- 未知错误",
            type: 0,
        })
    })

})

// 上传头像  
// multer 
var multer = require("multer");
var storage = multer.diskStorage({
    destination: function (req, file, cb) { // 头像存放的目录 
        cb(null, './public/avatar') // . 文件路径
    },
    filename: function (req, file, cb) { // 新的文件名 
        cb(null, Date.now() + "WH2008" + file.originalname); //  originalname 原文件名  1.jpg    145123213123WH20081.jpg
    }
})

var upload = multer({ storage: storage }).any(); // 可以上传任何格式的图片

router.post('/uploadavatar', upload, (req, res) => {
    checkToken(req, res, ({ username }) => {
        console.log(req.files)
        if (req.files) {
            var path = req.files[0].path;
            UserModel.updateMany({
                usernames: username,
            }, {
                $set: {
                    avatar: path
                }
            }).then(result => {
                res.json({
                    code: 200,
                    msg: "头像上传成功",
                    avatar: path,
                    result
                })
            }).catch(err => {
                res.json({
                    code: 500, // 500 统一失败  
                    msg: "服务器异常- 未知错误",
                    type: 0,
                })
            })
        }
    })
})


// 卖座数据接口
router.get("/maizuo", (req, res) => {
    var headers = req.headers;
    axios.get("https://m.maizuo.com/gateway?k=8204861", {
        params: req.query,
        headers: {
            'x-host': headers['x-host']
        },
    }).then(result => {

        res.json({
            code: 200,
            msg: "获取数据成功",
            ...result.data
        })
    }).catch(err => {
        res.json({
            code: 500, // 500 统一失败  
            msg: "服务器异常- 未知错误",
            type: 0,
            err
        })
    })
})

// 卖座数据接口
router.post("/getdata", (req, res) => {
    var headers = req.headers;
    var body = req.body;
    axios.post("https://m.maizuo.com/gateway?k=8204861", body, {
        headers: {
            'x-host': headers['x-host']
        },
    }).then(result => {
        res.json({
            code: 200,
            msg: "获取数据成功",
            ...result.data
        })
    }).catch(err => {
        res.json({
            code: 500, // 500 统一失败  
            msg: "服务器异常- 未知错误",
            type: 0,
            err
        })
    })
})

// router.post("/getNew", (req, res) => {
//     var headers = req.headers;
//     var body = req.body;
//     axios.post("", body, {
//         // headers: {
//         //     'x-host': headers['x-host']
//         // },
//     }).then(result => {
//         res.json({
//             code: 200,
//             msg: "获取数据成功",
//             ...result.data
//         })
//     }).catch(err => {
//         res.json({
//             code: 500, // 500 统一失败  
//             msg: "服务器异常- 未知错误",
//             type: 0,
//             err
//         })
//     })
// })

//// FM数据接口
router.get("/getfm", (req, res) => {
    var headers = req.headers;
    axios.get("https://api.kaolafm.com/api/v4/pagecontent/list", {
        params: req.query,
    }).then(result => {

        res.json({
            code: 200,
            msg: "获取数据成功",
            ...result.data
        })
    }).catch(err => {
        res.json({
            code: 500, // 500 统一失败  
            msg: "服务器异常- 未知错误",
            type: 0,
            err
        })
    })
})



router.post("/login/ceshi", (req, res) => { //测试封装
    var body = req.body
    console.log(body)
    UserModel.findOne(body, { _id: 0 }).then(result => {
        if (result) {
            var token = createToken({
                username: body.usernames,
                password: body.password
            })
            res.json({
                code: 200,
                type: 1,
                msg: "登录成功",
                token,
                result,
                body
            })
        } else {
            res.json({
                code: 200,
                type: 0,
                msg: "账号或密码错误"
            })
        }
    })
})



// 卖座数据接口
router.post("/getcode", (req, res) => {
    var headers = req.headers;
    var body = req.body;
    axios.post("https://m.maizuo.com/gateway?k=8204861", body, {
        headers: {
            'x-host': headers['x-host']
        },
    }).then(result => {
        res.json({
            code: 200,
            msg: "获取数据成功",
            ...result.data
        })
    }).catch(err => {
        res.json({
            code: 500, // 500 统一失败  
            msg: "服务器异常- 未知错误",
            type: 0,
            err
        })
    })
})


module.exports = router;